<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="$t('防御类别')" :v-if="dialogVisible" :visible.sync="dialogVisible" :width="lang === 'zh'?'900px':'950px'" top="10px" @close='close' class='categoryDialog'>
    <div class="categoryDown" :style="'max-width:' + (lang === 'zh'?'721px;':'781px;')">
      <!-- 检测项 -->
      <el-table :data="record.category_info" size='mini' class="categoryTableDown" :style="'width:' + (lang === 'zh'?'721px;':'781px;')" border @cell-click="cellClick" :row-class-name="tableRowClassName" :cell-class-name="tableCellClassName">
        <el-table-column prop="name" align="center" :label="$t('检测项')" :width="lang === 'zh'?'170':'230'">
          <template slot-scope="scope">
            <i :class="scope.row.status ? 'el-icon-tickets' : 'el-icon-folder'" style="margin-right:5px;"></i>{{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column prop="threshold" align="center" :label="$t('阈值')" width="100">
          <template slot-scope="scope">
            <div v-if="scope.row.index === rowIndex && scope.column.index === columnIndex && scope.column.label == $t('阈值')" class='inputnum'>
              <el-input v-emoji v-model="scope.row.threshold" ref='editInput' size="mini" @blur="thresholdBlur(scope)" />
            </div>
            <div class="inputnum" v-else>{{ scope.row.threshold }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="window" align="center" :label="$t('抖动窗口')" width="100">
          <template slot-scope="scope">
            <div v-if="scope.row.index === rowIndex && scope.column.index === columnIndex && scope.column.label == $t('抖动窗口')" class='inputnum'>
              <el-input v-emoji v-model="scope.row.window" ref='editInput' size="mini" @blur="thresholdBlur(scope)" />
            </div>
            <div class="inputnum" v-else>{{ scope.row.window }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="unit" align="center" :label="$t('单位')" width="100">
        </el-table-column>
        <el-table-column prop="status" align="center" :label="$t('开关')" width="100">
          <template slot-scope="scope">
            <el-switch :width="lang === 'zh'?55:70" v-if="scope.row.status" class="status switch" v-model="scope.row.status" active-color="#009966" @change="statusChange(scope.row)" inactive-color="#CCCCCC" active-value="on" inactive-value="off" :active-text="$t('开启')" :inactive-text="$t('关闭')">
            </el-switch>
          </template>
        </el-table-column>
      </el-table>
      <!-- 防御项 -->
      <el-table :data="record.category_info" size='mini' class="categoryTableDown" :style="'width:' + (lang === 'zh'?'721px;':'781px;')" row-key="name" border default-expand-all :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" style="margin-top:10px;" @cell-click="cellClickDown" :row-class-name="tableRowClassNameDown" :cell-class-name="tableCellClassNameDown">
        <el-table-column prop="name" :label="$t('防御项')" :width="lang === 'zh'?'170':'230'">
          <template slot-scope="{row}">
            <i :class="floodList[row.name] ? 'el-icon-folder' : 'el-icon-tickets'" style="margin-right:5px;"></i>{{ $t(row.name) }}
          </template>
        </el-table-column>
        <el-table-column prop="threshold" align="center" :label="$t('阈值')" width="100">
          <template slot-scope="scope">
            <div v-if="!floodList[scope.row.name] && scope.row.index === rowIndexDown && scope.column.index === columnIndexDown && scope.column.label == $t('阈值')" class='inputnum'>
              <el-input v-emoji v-model="scope.row.threshold" ref='editInputDown' size="mini" @blur="thresholdBlurDown(scope)" />
            </div>
            <div class="inputnum" v-else>{{ floodList[scope.row.name] ? '' : scope.row.threshold }}</div>
          </template>
          <!-- <template slot-scope="{row}">
            {{floodList[row.name]?'':row.threshold}}
          </template> -->
        </el-table-column>
        <el-table-column prop="window" align="center" :label="$t('抖动窗口')" width="100">
          <template slot-scope="scope">
            <div v-if="!floodList[scope.row.name] && scope.row.index === rowIndexDown && scope.column.index === columnIndexDown && scope.column.label == $t('抖动窗口')" class='inputnum'>
              <el-input v-emoji v-model="scope.row.window" ref='editInputDown' size="mini" @blur="thresholdBlurDown(scope)" />
            </div>
            <div class="inputnum" v-else>{{ floodList[scope.row.name] ? '' : scope.row.window }}</div>
          </template>
          <!-- <template slot-scope="{row}">
            {{floodList[row.name]?'':row.window}}
          </template> -->
        </el-table-column>
        <el-table-column prop="unit" align="center" :label="$t('单位')" width="100">
          <template slot-scope="{row}">
            {{ floodList[row.name] ? '' : row.unit }}
          </template>
        </el-table-column>
        <el-table-column prop="status" align="center" :label="$t('开关')" width="100">
          <template slot-scope="scope">
            <el-switch :width="lang === 'zh'?55:70" class="names switch" v-if="scope.row.status && !floodList[scope.row.name]" :disabled="record.category_info[floodSlot[scope.row.protype]].status === 'off'" v-model="scope.row.status" active-color="#009966" inactive-color="#CCCCCC" active-value="on" inactive-value="off" :active-text="$t('开启')" :inactive-text="$t('关闭')">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="action" align="center" :label="$t('动作')" width="150">
          <template slot-scope="scope">
            <el-select v-model="scope.row.action" v-if="scope.row.action && (scope.row.kind == 1)" size='mini' filterable>
              <el-option v-for="item in actionObjectiveList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <el-select v-model="scope.row.action" v-if="scope.row.action && (scope.row.kind == 2)" size='mini' filterable>
              <el-option v-for="item in actionSourceList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <el-select v-model="scope.row.action" v-if="scope.row.action && (scope.row.kind == 3)" size='mini' filterable>
              <el-option v-for="item in actionAgentList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { getCategory, editCategory } from '@/api/safe/ddos'
// import { inputClass } from '@/utils/input-class.js'
export default {
  name: 'CategoryDialog',
  data () {
    return {
      dialogVisible: false,
      lang: this.$i18n.locale,
      rowIndex: -1, // 行索引
      columnIndex: -1,
      rowIndexDown: -1, // 行索引
      columnIndexDown: -1,
      record: {
        name: '',
        category_info: []
      },
      recordCopy: {
        name: '',
        category_info: []
      },
      actionSourceList: [
        { label: this.$t('丢弃'), value: 'drop' },
        { label: this.$t('黑名单'), value: 'black' }
      ],
      actionObjectiveList: [
        { label: this.$t('丢弃'), value: 'drop' }
      ],
      actionAgentList: [
        { label: this.$t('SYN代理'), value: 'synproxy' }
      ],
      floodList: {
        'TCP FLOOD': '防御 TCP类',
        'UDP FLOOD': '防御 UDP类',
        'ICMP FLOOD': '防御 ICMP类'
      },
      floodSlot: {}
    }
  },
  methods: {
    init (data) {
      this.dialogVisible = true
      this.record.name = data.name
      // this.$nextTick(() => {
      //   const data = ['editInput', 'editInputDown']
      //   inputClass(this.$refs, data)
      // })
      getCategory({ name: data.name }).then(res => {
        if (res.status === 0) {
          for (let item of res.info) {
            if (item.kind === 0) {
              let formData = item
              formData.children = []
              this.record.category_info.push(formData)
            } else {
              for (const index in this.record.category_info) {
                if (this.record.category_info[index].protype === item.protype) {
                  this.record.category_info[index].children.push(item)
                  break
                }
              }
            }
          }
          for (let item of this.record.category_info) {
            item.children = item.children.sort(this.compare('sid'))
          }
          for (const index in this.record.category_info) {
            this.floodSlot[this.record.category_info[index].protype] = index
          }
        }
      })
    },
    compare (property) {
      return function (a, b) {
        var value1 = a[property]
        var value2 = b[property]
        return value1 - value2
      }
    },
    changeStatus (val) {
      this.record.status = val ? 'on' : 'off'
    },
    submit () {
      let formData = {
        name: null,
        category_info: []
      }
      formData.name = this.record.name
      for (let item of this.record.category_info) {
        if (item.kind === 0) {
          if (this.submitRuleChange(item.threshold) || this.submitRuleChange(item.window)) {
            return
          }
          let data = JSON.parse(JSON.stringify(item))
          delete data.children
          formData.category_info.push(data)
          for (let child of item.children) {
            if (child.kind !== 3 && (this.submitRuleChange(child.threshold) || this.submitRuleChange(child.window))) {
              return
            }
            formData.category_info.push(child)
          }
        }
      }
      formData.category_info = JSON.stringify(formData.category_info)
      editCategory(formData).then(res => {
        if (res.status === 0) {
          this.$message({
            message: this.$t('编辑成功'),
            type: 'success'
          })
          this.close()
        }
      })
    },
    close () {
      this.dialogVisible = false
      this.record = Object.assign({}, this.recordCopy)
      this.record.category_info = []
    },
    statusChange (data) {
      if (data.status === 'off') {
        for (let item of this.record.category_info) {
          if (data.protype === item.protype) {
            for (let item1 of item.children) {
              item1.status = 'off'
            }
          }
        }
      }
    },
    tableRowClassName ({ row, rowIndex }) {
      row.index = rowIndex
    },
    // 把每一列的索引加到列数据中
    tableCellClassName ({ column, columnIndex }) {
      column.index = columnIndex
    },
    // 单元格被点击时会触发该事件
    cellClick (row, column, cell, event) {
      // console.log(row, '单条数据', column, '列信息', cell, 'td实例', event)
      if ((column.label === this.$t('阈值') || column.label === this.$t('抖动窗口')) && row.kind !== 3) {
        this.rowIndex = row.index
        this.columnIndex = column.index
        this.$nextTick(() => {
          this.$refs['editInput'].focus()
        })
      }
    },
    // 输入框失去焦点事件（初始化中间变量）
    thresholdBlur (scope) {
      this.rowIndex = -1
      this.columnIndex = -1
    },
    tableRowClassNameDown ({ row, rowIndex }) {
      if (!this.floodList[row.name]) {
        row.index = rowIndex
      }
    },
    // 把每一列的索引加到列数据中
    tableCellClassNameDown ({ column, columnIndex }) {
      column.index = columnIndex
    },
    // 单元格被点击时会触发该事件
    cellClickDown (row, column, cell, event) {
      // console.log(row, '单条数据', column, '列信息', cell, 'td实例', event)
      if (!this.floodList[row.name] && (column.label === this.$t('阈值') || column.label === this.$t('抖动窗口')) && row.kind !== 3) {
        this.rowIndexDown = row.index
        this.columnIndexDown = column.index
        this.$nextTick(() => {
          this.$refs['editInputDown'].focus()
        })
      }
    },
    // 输入框失去焦点事件（初始化中间变量）
    thresholdBlurDown (scope) {
      this.rowIndexDown = -1
      this.columnIndexDown = -1
    },
    submitRuleChange (value) {
      if (String(value).trim() === '') {
        this.$messages.error(this.$t('不能为空'))
        return true
      } else if (!this.isInteger(value)) {
        this.$messages.error(this.$t('只能输入整数'))
        return true
      } else {
        return false
      }
    },
    isInteger (value) {
      return (!isNaN(value) && (parseInt(value).toString().length === String(Number(value)).length))
    }
  }
}
</script>
<style lang="scss" scoped>
.categoryDialog {
  .ivu-switch-checked {
    border-color: #5fb878;
    background-color: #5fb878;
  }
}

.categoryDown {
  align-items: flex-start;
  margin: 0 auto;
  // max-width: 781px;
  overflow: auto;
  width: 100%;
}

// .categoryTableDown {
// width: 781px;
// }
</style>
